//
//  KoiAuthenticator.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 14.04.25.
//

import Foundation
import Alamofire

final class KoiAuthenticator : Authenticator {
    func apply(_ credential: KoiAuthenticationCredential, to urlRequest: inout URLRequest) {
        urlRequest.headers.add(.authorization(bearerToken: credential.accessToken))
    }
    
    func refresh(_ credential: KoiAuthenticationCredential, for session: Session, completion: @escaping (Result<KoiAuthenticationCredential, any Error>) -> Void) {
        // 刷新 token
        print("refresh \(credential.refreshToken)")
        KoiAccountingNetApi.standard.refreshToken() { result in
            switch result {
            case .success(let success):
                // 保存新的 token
                KoiTokenStore.saveToken(token: success)
                completion(.success(KoiAuthenticationCredential.shared))
            case .failure(let failure):
                // print("refresh fail \(failure)")
                print("refresh fail \(failure)")
                if failure.responseCode == 401 {
                    //重新登录
                    completion(.failure(failure))
                    NotificationCenter.default.post(name: .tokenInvalid, object: nil)
                } else {
                    completion(.failure(AFError.explicitlyCancelled))
                }
            }
        }
    }
    
    func didRequest(_ urlRequest: URLRequest, with response: HTTPURLResponse, failDueToAuthenticationError error: any Error) -> Bool {
        print("didRequest")
        return response.statusCode == 401
    }
    
    func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: KoiAuthenticationCredential) -> Bool {
        print("isRequest \(urlRequest)")
        let bearerToken = HTTPHeader.authorization(bearerToken: credential.accessToken).value
        return urlRequest.headers["Authorization"] == bearerToken
    }
    
}
